<template>
  <custom-dialog
    ref="dialog" title="设置应用" width="600px" height="300px"
    :before-confirm="beforeConfirm" :on-confirm="onConfirm"
  >
    <el-form ref="form" :model="info" :rules="rules" label-width="120px">
      <el-form-item label="选择应用" prop="applicationIds">
        <el-checkbox-group v-model="info.applicationIds">
          <el-checkbox class="checkbox-item" v-for="option in appsOption" :key="option.id" :label="option.id">
            {{ option.applicationName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/custom-dialog'
import { queryList } from '@/api/sysApplication'
import { batchByRoleApplication, loadRoleIdByApplicationList } from '@/api/sysRoleApplication'

const api = {
  queryList,
  batchByRoleApplication,
  loadRoleIdByApplicationList
}
export default {
  name: 'set-app-modal',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  components: { CustomDialog },
  data () {
    return {
      info: {
        applicationIds: []
      },
      rules: {
        applicationIds: [{ required: true, message: '请选择应用' }]
      },
      appsOption: []
    }
  },
  methods: {
    getApplicationIdsByRoleId () {
      return api.loadRoleIdByApplicationList(this.roleId).then(res => {
        if (res.code === 200) {
          this.info.applicationIds = res.data
        }
      })
    },
    getAppsOption () {
      return api.queryList().then(res => {
        if (res.code === 200) {
          this.appsOption = res.data
        }
      })
    },
    open () {
      this.info = this.$options.data().info
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.getAppsOption()
      this.getApplicationIdsByRoleId()
      this.$nextTick(() => {
        this.$refs.dialog.open()
      })
    },
    beforeConfirm () {
      return this.$refs.form.validate()
    },
    onConfirm (close) {
      const params = this.info.applicationIds.map(v => ({
        roleId: this.roleId,
        applicationId: v
      }))
      return api.batchByRoleApplication(params).then(res => {
        if (res.code === 200) {
          this.$emit('save-success')
          this.$message.success('保存成功')
          close()
        }
      })
    }
  }
}
</script>

<style scoped>
.checkbox-item {
  display: block;
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
